<template>
  <div>
    <van-nav-bar title="登录" />

    <van-form @submit="login">
      <van-field
        required
        v-model="phone"
        name="phone"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.phone"
      />
      <van-field
        required
        v-model="code"
        type="number"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="登录中..."
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  data() {
    return {
      isLoading: false,
      phone: '15155544284',
      code: '246810',
      rules: {
        // 手机号的校验
        phone: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern:
              // 手机号的格式 正则
              /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号格式不正确'
          }
        ],
        // 验证码
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async login() {
      this.isLoading = true
      try {
        const res = await userLogin(this.phone, this.code)
        console.log(res)
        // alert('登录成功')
        this.setToken(res.data)
        // 用户没有登录 当登录完成后 跳转到刚开始阅读的页面
        const back = this.$route.query.back || '/user'
        const flag = this.$route.query.flag
        console.log(back)
        console.log(flag)
        if (flag) {
          return this.$router.back()
        }
        this.$router.push(back)

        this.$toast.success('登录成功')
      } catch {
        this.$toast.fail('登录失败')
      }
      this.isLoading = false
    }
  }
}
</script>

<style></style>
